import { LocalStorage } from "node-localstorage";

const localstorage = new LocalStorage("./search");

export function sleep(time: number) {
  return new Promise((resolve) => {
    const timer = setTimeout(() => {
      timer && clearTimeout(timer);
      resolve(null);
    }, time * 1000);
  });
}

export function parseReg(pattern: string | RegExp): RegExp {
  return Object.prototype.toString.call(pattern) == "[object RegExp]"
    ? (pattern as RegExp)
    : new RegExp(pattern);
}

function initData() {
  localstorage.setItem("data1", "data1");
  localstorage.setItem("abc", "123");
}

function keys() {
  return localstorage._keys;
}

function getAll(): {} {
  let storeInfo = {};
  for (const key of keys()) {
    const data = localstorage[key];
    data && (storeInfo[key] = data);
  }
  return storeInfo;
}

function clear() {
  localstorage.clear();
}

export const storeUtil = {
  initData,
  getAll,
  keys,
  clear,
  /**
   * 设置值 并支持设置的值可以过期
   * @param key
   * @param value
   * @param expired 天 (1天: 864e5)
   */
  set(key: string, value: any, expiredo?: number): void {
    localstorage.setItem(key, value);
    expiredo && localstorage.setItem(`${key}_expire`, Date.now() + expiredo * 864e5);
  },

  /**
   * 获取数据
   * 注意:
   * 1、过期的数据应该删除并返回 null
   * 2、应在每次get的时候 判断数据过期情况
   * 3、只要数据过期了就应该删除
   * @param key
   */
  get(key: string): string | null {
    this.beforeGetDataCheck();
    return localstorage.getItem(key);
    // return v
    // const vExpire = localstorage.getItem(`${key}_expire`);
    // if(!vExpire || vExpire > Date.now()) return v
    // this.remove(key)
    // return null
  },
  // 获取数据之前校验数据的过期情况
  beforeGetDataCheck() {
    const keys = this.findByReg(/_expire$/, "keys");
    keys &&
      keys.forEach((key: string) => {
        if (localstorage[key] < Date.now()) {
          this.remove(key.split("_expire")[0]);
        }
      });
  },
  /**
   * 按key删除数据, 注意删除过期flag
   * @param key
   */
  remove(key) {
    localstorage.removeItem(key);
    localstorage.removeItem(`${key}_expire`);
  },
  // 多个key删除数据
  removeByKeys(keys: string[]) {
    keys.forEach(this.remove);
  },
  /**
   * 查找符合正则条件的数据
   * @param pattern
   * @param mode ['keys','values','entries']
   * @returns {string[] | {[ key as string]: any}}
   */
  findByReg(pattern: string | RegExp, mode: "keys" | "values" | "entries" = "keys"): [] | {} {
    const reg: RegExp = parseReg(pattern);
    if (mode === "keys") {
      return keys().filter((item: string) => reg.test(item));
    }
    if (mode === "values") {
      return keys()
        .map((item: string) => storeUtil.get(item))
        .filter(() => reg.test);
    }
    if (mode === "entries") {
      return keys()
        .filter(() => reg.test)
        .reduce((pre, cur) => {
          return localstorage[cur] && (pre[cur] = localstorage[cur]), pre;
        }, {});
    }
    return {};
  },
};
